/***mui初始化****/
var localStoragerManager = require('script/localStorageManagers.js');
var storageUtils = require('script/localStorageUtils.js');
var mobileFrame = require('scripts/Core/MobileFrame.js');
mui.init();
//子页面
var subpages = ['synccourse/courseindex.html', 'scancode/barcode.html', 'selfcenter/selfindex.html', 'offlinedown/offlineindex.html'];
var subpage_style = {
	top: '60px',
	bottom: '51px'
};

var aniShow = {};
//创建子页面，首个选项卡页面显示，其它均隐藏；
mui.plusReady(function() {
	document.getElementById('setting-a').style.visibility = 'hidden';
	mui.preload({
		url: 'login.html',
		id: 'login',
		styles: {
			top: '0px',
			bottom: '0px'
		}
	});

	//judgelogin();
	//isFirstLogin();

	var self = plus.webview.currentWebview();
	for (var i = 0; i < 4; i++) {
		var temp = {};
		var sub = plus.webview.create(subpages[i], subpages[i], subpage_style);
		if (i > 0) {
			sub.hide();
		} else {
			temp[subpages[i]] = "true";
			mui.extend(aniShow, temp);
		}
		self.append(sub);
	}
	//消息标志
	setNoreadTag();
});
//当前激活选项
var activeTab = subpages[0];
var title = document.getElementById("title");
mui('.mui-bar-tab').on('release', 'a', function(e) {
	//alert(this.innerHTML);
});
//选项卡点击事件
mui('.mui-bar-tab').on('tap', 'a', function(e) {
	//mobileFrame.IsNetWorkCanUse();
	var targetTab = this.getAttribute('href');
	if (targetTab == activeTab) {
		return;
	}
	var thistitle = this.querySelector('.mui-tab-label').innerHTML;
	//如果是学习中心隐藏头部
	if (thistitle == '学习中心') {
		title.innerHTML = ' ';
		document.getElementById('setting-a').style.visibility = 'visible';
		loadUserAjax();
	} else {
		//更换标题
		title.innerHTML = thistitle;
		document.getElementById('setting-a').style.visibility = 'hidden';
	}
	//切换到离线下载页签，刷新
	if(thistitle == '离线下载'){
		var downWebView = plus.webview.getWebviewById("offlinedown/offlineindex.html");
	    downWebView.evalJS("initDown()");
	}

	//显示目标选项卡
	//若为iOS平台或非首次显示，则直接显示
	if (mui.os.ios || aniShow[targetTab]) {
		var s = plus.webview.show(targetTab);
	} else {
		//否则，使用fade-in动画，且保存变量
		var temp = {};
		temp[targetTab] = "true";
		mui.extend(aniShow, temp);
		plus.webview.show(targetTab, "fade-in", 300);
	}
	//隐藏当前;
	//console.log(activeTab);
	plus.webview.hide(activeTab);
	//更改当前活跃的选项卡
	activeTab = targetTab;
});
//自定义事件，模拟点击“首页选项卡”
document.addEventListener('gohome', function() {
	var defaultTab = document.getElementById("defaultTab");
	//模拟首页点击
	mui.trigger(defaultTab, 'tap');
	//切换选项卡高亮
	var current = document.querySelector(".mui-bar-tab>.mui-tab-item.mui-active");
	if (defaultTab !== current) {
		current.classList.remove('mui-active');
		defaultTab.classList.add('mui-active');
	}
});
//打开设置页面
mui('header').on('tap', '#setting-a', function() {
	mui.openWindow({
		url: 'setup/setupindex.html',
		id: 'setup/setupindex',
	});
});
//打开消息页面
mui('header').on('tap', '#message', function() {
	document.getElementById('newmsg').className = 'newmsg';
	
	mui.openWindow({
		url: 'message/msgindex.html',
		id: 'message/msgindex',
		styles:getStyles(),
		waiting:{
			autoShow:false
		}
	});
});
//首页返回键处理
//处理逻辑：1秒内，连续两次按返回键，则退出应用；
var first = null;
mui.back = function() {
	//首次按键，提示‘再按一次退出应用’
	if (!first) {
		first = new Date().getTime();
		mui.toast('再按一次退出应用');
		setTimeout(function() {
			first = null;
		}, 1000);
	} else {
		if (new Date().getTime() - first < 1000) plus.runtime.quit();
	}
};
//判断是否已经登陆
function judgelogin() {
	//			//测试语句
	//			localStorage.removeItem('user');
	//判断是否已经登录成功//localstorage在页面关闭的时候也同样存在，sessionstorage页面关闭数据不存在
	var ifLogin = true;
	var userid = localStoragerManager.getUseridSession();
	if (userid == null || userid == '') {
		ifLogin = false;
		mui.openWindow({
			url: 'login.html',
			id: 'login',
			show: {
				aniShow: 'pop-in'
			},
			styles: {
				popGesture: 'hide'
			},
			waiting: {
				autoShow: false
			}
		});
		//indexWebview.close();
	}else{
		loadUserAjax();
	}
	return ifLogin;
}
//ajax加载
		function loadUserAjax(){
			var userid = localStoragerManager.getUseridSession();
			var url=serverAjax+'mobile/user/getUser.do';
			mui.ajax(url,{
				data:{userid:userid}, 
				type:'post',
				dataType:'json',
				timeout:10000,
				success:function(data){
					if(data==null||data.length==0)return;
					var userinfo=data.ext1;
					localStoragerManager.setUserinfoSession(userinfo);
					var selfcenter=plus.webview.getWebviewById('selfcenter/selfindex.html');
					var userinfoJSON = JSON.parse(userinfo);
					var path=userinfoJSON.path;
					if(path!=null&&path!='')selfcenter.evalJS("setTouxiang('"+fileServerAjax+path+"')");
				},
				error:function(e1,e2,e3){
					console.log(e1);
					ajaxErrorTip();
				}
			});
		}
//是否初次进入
function isFirstLogin() {
	var isfirst = storageUtils.getSessionItem("isfirst");
	var result = false;
	if (isfirst == null || isfirst.length == 0) {
		mui.openWindow({
			url: 'startpage.html',
			id: 'startpage',
	     	waiting:{
               autoShow:false//自动显示等待框，默认为true
            }
		});
		storageUtils.setSessionItem('isfirst', 'true');
		result = true;
	}
	//storageUtils.removeSessionItem('isfirst');
	return result;
};
//是否有未读消息
function setNoreadTag(){
	setInterval("setNoreadTag1()",60000);//1000为1秒钟
}
function setNoreadTag1() {
	var className=document.getElementById('newmsg').className;
	if(className=='newmsg m1')return;
	//console.log("定时刷新未读消息！");
	var userid = localStoragerManager.getUseridSession();
	if(userid==null)return;
	var url = serverAjax + 'mobile/message/getMsgList.do';
	mui.ajax(url, {
		data: {
			userid: userid
		},
		type: 'post',
		dataType: 'json',
		timeout: 10000,
		success: function(data) {
			if (data == null || data.length == 0) return;
			for (var i = 0; i < data.length; i++) {
				var msg = data[i];
				if (msg.status == -1) {
					//console.log("有新消息了！");
					document.getElementById('newmsg').className = 'newmsg m1';
					break
				}
			}
		},
		error: function(e1, e2, e3) {
			ajaxErrorTip();
			console.log(e1);
		}
	});
}